/**
 * 定义ui公共模块
 */
(function(window, angular, undefined){

	var component = angular.module('water.common.component',['water.common.formCheck']);
	
	/**
	 * 基础下拉组件
	 */
	component.directive("gscomSelect", function($rootScope) {
		return { 
			transclude: false,    // 不复制原始HTML内容 
		    restrict: "E",        // 指令是一个元素 (并非属性) 
		    require : "ngModel",
		    replace: true,        // 使用模板替换原始标记 
		    scope: {              // 设置指令对于的scope 
		      id: "@",          // id 值传递 （字符串，单向绑定）
		      pollType:"@",
		      width:"@width",
		      model:"=ngModel",
		      componentObject:"=componentObject",
		      data: "=",
		      change:"&ngChange"
		    },
		    template:'',
		    link: function ($scope, element, attrs, controller) {
		    	$scope.selectItem = null;
		    	
		    	try{
		    		/**
			    	 * 暴露接口
			    	 */
			    	$scope.componentObject = {
			    			name:attrs.ngModel,
			    			/**
			    			 * 设置数据,并渲染组件，因为跟easyui结合，
			    			 * 所以在业务逻辑中，如果data发生变化，组件的数据不会自动更新，
			    			 * 需要手动setData
			    			 */
			    			setData:function(data){
			    				$scope.data = data;
			    				$scope.renderData($scope.data);
			    			}
			    	}
		    	} catch (e) {
					console.log(e)
				}
		    	
		    	/**
		    	 * 使用easyui渲染组件
		    	 */
		    	$scope.renderData = function(data){
		    		/**
		    		 * 渲染组件
		    		 */
		    		element.combobox({
			    	    data:data,
			    	    valueField:'k',
			    	    textField:'v',
			    	    editable:true,
			    	    onSelect:function(record){
			    	    	/**
			    	    	 * 下拉选择事件，设置当前选择的项
			    	    	 */
			    	    	safeApply($scope,(function(){
			    	    		$scope.selectItem = record;
				    	    	/**
				    	    	 * 在对外的接口上设置选中的项目，提供给父子组件使用
				    	    	 */
				    	    	$scope.componentObject.selectItem = $scope.selectItem;
				    	    	if(record){
				    	    		$scope.model = record.k;
				    	    	}
	                         }));
			    	    }
			    	});
		    		/**
		    		 * 如有有值，设置之
		    		 */
		    		if($scope.model){
		    			var bingo = false;
		    			for(var i=0;i<data.length;i++){
		    				var k = data[i].k
		    				if(k == $scope.model){
		    					element.combobox("select",$scope.model);
		    					bingo = true;
		    					break;
		    				}
		    			}
		    			
		    			if(!bingo){
		    				$scope.model = null;
		    			}
		    		}
		    	}
		    	
		    	function safeApply(scope, fn) {  
		    	    (scope.$$phase || scope.$root.$$phase) ? fn() : scope.$apply(fn);  
		    	}  
		    	
		    	controller.$render = function(){
		    		var viewValue = controller.$viewValue;
		    		$scope.model = viewValue;
		    		element.combobox("select",viewValue);
		    		if($scope.change()){
	    				$scope.change()($scope.selectItem);
		    		}
		    	}
		    	
		    	/**
		    	 * 初始化组件
		    	 */
		    	function _init(){
		    		$scope.renderData($scope.data);
		    	}
		    	_init();
		    }
		  } 
	});
	/**
	 * 下拉字典组件
	 */
	component.directive("comDomainSelect", function($domainService,$q) {
		return { 
			transclude: false,    // 不复制原始HTML内容 
		    restrict: "A",        // 指令是一个元素 (并非属性) 
		    require : "ngModel",
		    replace: true,        // 使用模板替换原始标记 
		    scope: {              // 设置指令对于的scope 
		      model:"=ngModel",
		      domainName:"@domainName",
		      parentId:"@parentId",
		      componentObject:"=componentObject",
		      childComponentObject:"=childComponentObject",
		      parentComponentObject:"=parentComponentObject",
		      change:"&ngChange"
		    }, 
		    template:             // 嵌套使用组件，需要在外面包一层
		    	'<div><com-select data="data" ng-model="model" ng-change="change()" component-object="comSelectComponent"></com-select></div>',
		    link: function ($scope, element, attrs, controller) {
		    	$scope.comSelectComponent;
		    	
		    	try{
		    		/**
			    	 * 公共选择组件
			    	 */
			    	$scope.componentObject = {
			    			name:attrs.ngModel,
			    			setData : function(data){
			    				$scope.comSelectComponent.setData(data);
			    			},
			    			updateByParentId:function(parentId){
			    				/**
			    				 * 暴露给父组件的接口，当父组件选择新项后，根据新项更新本组件的下拉数据
			    				 */
			    				$scope.getDomainData(parentId).then(function(data){
			    					$scope.comSelectComponent.setData(data);
				    			});
			    			}
			    	};
		    	} catch (e) {
					console.log(e)
				}
		    	
		    	
		    	/**
		    	 * 获取字典数据，并转化成组件支持的数据格式
		    	 */
		    	$scope.getDomainData = function(id){
		    		var deferred = $q.defer();
					var promise = deferred.promise;
					
					$domainService.getList($scope.domainName,id).then(function(d){
			    		var data = [];
			    		if(d){
			    			for(var i=0;i<d.length;i++){
				    			data.push({
				    				v:d[i].text,
				    				k:d[i].id
				    			});
				    		}
			    		}   		
			    		
			    		deferred.resolve(data);
			    		
			    	});
					return promise;
		    	}
		    	
		    	/**
		    	 * 初始化组件数据
		    	 */
		    	function initData(){
	    			$scope.getDomainData($scope.parentId).then(function(data){
		    			$scope.comSelectComponent.setData(data);
		    		});
	    			if(attrs.childComponentObject){
	    				var dereg = $scope.$watch('childComponentObject', function(){
	    					updateChildComponentData();
	    					dereg();
	    				});
	    			}
		    	}
		    	
		    	/**
		    	 * 更新子控件的数据
		    	 */
		    	function updateChildComponentData(){
		    		if($scope.childComponentObject){
		    			$scope.childComponentObject.updateByParentId($scope.model);
		    		}
		    	}
		    	
		    	controller.$render = function(){
		    		$scope.model = controller.$viewValue;
		    		updateChildComponentData();
		    	}
		    	
		    	initData();
		    	
		    }
		  } 
	});
	
	/**
	 * 自定义字典组件
	 */
	component.directive("comCustomersDomainSelect", function($domainService,$q) {
		return { 
			transclude: false,    // 不复制原始HTML内容 
		    restrict: "A",        // 指令是一个元素 (并非属性) 
		    require : "ngModel",
		    replace: true,        // 使用模板替换原始标记 
		    scope: {              // 设置指令对于的scope 
		      model:"=ngModel",
		      tableName:"@tableName",
		      keyField:"@keyField",
		      valueField:"@valueField",
		      parentField:"@parentField",
		      parentId:"@parentId",
		      componentObject:"=componentObject",
		      childComponentObject:"=childComponentObject",
		      parentComponentObject:"=parentComponentObject",
		      change:"&ngChange"
		    }, 
		    template:             // 嵌套使用组件，需要在外面包一层
		    	'<div ><com-select data="data" ng-model="model"   ng-change="onChange" component-object="comSelectComponent"></com-select></div>',
		    link: function ($scope, element, attrs, controller) {
		    	$scope.comSelectComponent;
		    	
		    	/**
		    	 * 判断这个变量有没有在view上配置，如果没有配置的话，就不设置
		    	 * 否则会报错
		    	 */
		    	try{
		    		/**
			    	 * 公共选择组件
			    	 */
			    	$scope.componentObject = {
			    			name:attrs.ngModel,
			    			setData : function(data){
			    				$scope.comSelectComponent.setData(data);
			    			},
			    			updateByParentId : function(pid){
			    				$scope.getDomainData(pid).then(function(data){
			    					$scope.comSelectComponent.setData(data);
			    				});
			    			}
			    	};
		    	} catch (e) {
					console.log(e)
				}
		    	
		    	$scope.onChange = function(){
		    		if($scope.change()){
		    			$scope.change()($scope.comSelectComponent.selectItem)
		    		}
		    	}
		    	
		    	/**
		    	 * 获取字典数据，并转化成组件支持的数据格式
		    	 */
		    	$scope.getDomainData = function(id){
		    		var deferred = $q.defer();
					var promise = deferred.promise;
					
					$domainService.getCustomersList($scope.tableName,$scope.keyField,$scope.valueField,$scope.parentField,id).then(function(d){
			    		var data = [];
			    		for(var i=0;i<d.length;i++){
			    			data.push({
			    				v:d[i].V,
			    				k:d[i].K
			    			});
			    		}
			    		deferred.resolve(data);
			    		
			    	});
					return promise;
		    	}
		    	
		    	/**
		    	 * 初始化组件数据
		    	 */
		    	function initData(){
	    			$scope.getDomainData($scope.parentId).then(function(data){
		    			$scope.comSelectComponent.setData(data);
		    		});
	    			if(attrs.childComponentObject){
	    				var dereg = $scope.$watch('childComponentObject', function(){
	    					updateChildComponentData();
	    					dereg();
	    				});
	    			}
		    	}
		    	
		    	/**
		    	 * 更新子控件的数据
		    	 */
		    	function updateChildComponentData(){
		    		if($scope.model && $scope.childComponentObject){
		    			$scope.childComponentObject.updateByParentId($scope.model);
		    		}
		    	}
		    	
		    	controller.$render = function(){
		    		$scope.model = controller.$viewValue;
		    		updateChildComponentData();
		    	}
		    	
		    	initData();
		    	
		    }
		  } 
	});
	
	
	/**
	 * 字典check组件
	 */
	component.directive("comDomainMulitCheck", function($domainService,$q) {
		return { 
			transclude: false,    // 不复制原始HTML内容 
		    restrict: "A",        // 指令是一个元素 (并非属性) 
		    require : "ngModel",
		    replace: true,        // 使用模板替换原始标记 
		    scope: {              // 设置指令对于的scope 
		      model:"=ngModel",
		      mulit:"@ngMulit",
		      domainName:"@domainName",
		      parentId:"@parentId",
		      modelKeyname:'@modelKeyname',
		      change:"&ngChange",
		      componentObject:"=componentObject",
		      childComponentObject:"=childComponentObject"
		    }, 
		    template:             // 嵌套使用组件，需要在外面包一层
		    	'<div><com-mulit-check ng-change="change" model-keyname="modelKeyname" ng-model="model" data="data" component-object="baseComponentObject"></com-mulit-check></div>',
		    link: function ($scope, element, attrs, controller) {
		    	
		    	$scope.baseComponentObject;
		    	
		    	try{
		    		/**
			    	 * 暴露接口
			    	 */
			    	$scope.componentObject = {
			    			updateByParentId:function(parentId){
			    				/**
			    				 * 暴露给父组件的接口，当父组件选择新项后，根据新项更新本组件的下拉数据
			    				 */
			    				$scope.getDomainData(parentId).then(function(data){
			    					$scope.baseComponentObject.setData(data);
				    			});
			    			}
			    	};
		    	} catch (e) {
					console.log(e)
				}
		    	
		    	/**
		    	 * 获取字典数据，并转化成组件支持的数据格式
		    	 */
		    	$scope.getDomainData = function(id){
		    		var deferred = $q.defer();
					var promise = deferred.promise;
					
					$domainService.getList($scope.domainName,id).then(function(d){
			    		var data = [];
			    		for(var i=0;i<d.length;i++){
			    			data.push({
			    				v:d[i].text,
			    				k:d[i].id
			    			});
			    		}
			    		deferred.resolve(data);
			    		
			    	});
					return promise;
		    	}
		    	
		    	/**
		    	 * 更新子控件的数据
		    	 */
		    	function updateChildComponentData(){
		    		if($scope.model && $scope.childComponentObject){
		    			$scope.childComponentObject.updateByParentId($scope.model);
		    		}
		    	}
		    	
		    	controller.$render = function(){
		    		updateChildComponentData();
		    	}
		    	
		    	/**
		    	 * 初始化组件数据
		    	 */
		    	function initData(){
	    			$scope.getDomainData($scope.parentId).then(function(data){
		    			$scope.data = data;
		    		});
		    	}
		    	
		    	initData();
		    }
		  } 
	});
	
	/**
	 * 自定义字典check组件
	 */
	component.directive("comCustomerDomainMulitCheck", function($domainService,$q) {
		return { 
			transclude: false,    // 不复制原始HTML内容 
		    restrict: "A",        // 指令是一个元素 (并非属性) 
		    require : "ngModel",
		    replace: true,        // 使用模板替换原始标记 
		    scope: {              // 设置指令对于的scope 
		      model:"=ngModel",
		      uiType:"=uiType",
		      tableName:"@tableName",
		      keyField:"@keyField",
		      valueField:"@valueField",
		      parentField:"@parentField",
		      componentObject:"=componentObject",
		      childComponentObject:"=childComponentObject",
		      parentComponentObject:"=parentComponentObject",
		      modelKeyname:'@modelKeyname',
		      getData:'&getData',
		      change:"&ngChange"
		    }, 
		    template: function( element, attrs){
		    	if(attrs.uiType == 'checkbox'){
		    		return '<div><com-mulit-check ng-change="change()" model-keyname="modelKeyname" ui-type="checkbox" ng-model="model" data="data" component-object="comSelectComponent"></com-mulit-check></div>';
		    	}
		    	else{
		    		return '<div><com-mulit-check ng-change="change()" model-keyname="modelKeyname" ng-model="model" data="data" component-object="comSelectComponent"></com-mulit-check></div>';
		    	}
		    },
		    link: function ($scope, element, attrs, controller) {

		    	try {
		    		$scope.componentObject = {
			    			name:attrs.ngModel,
			    			setData : function(data){
			    				$scope.comSelectComponent.setData(data);
			    			},
			    			updateByParentId : function(pid){
			    				$scope.getDomainData(pid).then(function(data){
			    					$scope.comSelectComponent.setData(data);
			    				});
			    			}
			    	};
				} catch (e) {
					console.log(e)
				}
		    		
		    	
		    	/**
		    	 * 获取字典数据，并转化成组件支持的数据格式
		    	 */
		    	$scope.getDomainData = function(id){
		    		var deferred = $q.defer();
					var promise = deferred.promise;
					
					if($scope.getData && $scope.getData()){
		    			$scope.getData()(id).then(function(d){
		    				if(!d){
		    					deferred.resolve([]);
		    				}
		    				else{
		    					var data = [];
					    		for(var i=0;i<d.length;i++){
					    			data.push({
					    				v:d[i][$scope.valueField],
					    				k:d[i][$scope.keyField]
					    			});
					    		}
					    		deferred.resolve(data);
		    				}
		    			});
		    		}
					else{
						$domainService.getCustomersList($scope.tableName,$scope.keyField,$scope.valueField,$scope.parentField,id).then(function(d){
				    		var data = [];
				    		for(var i=0;i<d.length;i++){
				    			data.push({
				    				v:d[i].V,
				    				k:d[i].K
				    			});
				    		}
				    		deferred.resolve(data);
				    	});
					}
						
		    		return promise;
		    	}
		    	
		    	/**
		    	 * 初始化组件数据
		    	 */
		    	function initData(){
	    			$scope.getDomainData($scope.parentId).then(function(data){
		    			$scope.data = data;
		    		});
		    	}
		    	
		    	/**
		    	 * 初始化组件数据
		    	 */
		    	function initData(){
	    			$scope.getDomainData($scope.parentId).then(function(data){
		    			$scope.comSelectComponent.setData(data);
		    		});
	    			if(attrs.childComponentObject){
	    				var dereg = $scope.$watch('childComponentObject', function(){
	    					if($scope.childComponentObject){
	    						updateChildComponentData();
	    						dereg();
	    					}
	    				});
	    			}
		    	}
		    	
		    	/**
		    	 * 更新子控件的数据
		    	 */
		    	function updateChildComponentData(){
		    		if($scope.model && $scope.childComponentObject){
		    			$scope.childComponentObject.updateByParentId($scope.model);
		    		}
		    	}
		    	
		    	controller.$render = function(){
		    		$scope.model = controller.$viewValue;
		    		updateChildComponentData();
		    	}
		    	
		    	initData();
		    }
		  } 
	});
	
}(window, angular));